import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'

export async function GET(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const project = await db.researchProject.findUnique({
      where: { id: params.id },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    if (!project) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }
    
    // 转换数据格式以匹配前端需要的电机项目格式
    const motorProject = {
      id: project.id,
      name: project.name || project.projectTitle,
      customer: project.customerName || '',
      salesperson: project.applicantName || '',
      requirements: project.description || '',
      description: project.applicationType || '',
      status: project.level1?.toLowerCase() || 'pending',
      motorType: project.motorType || '',
      motorPower: project.motorPower || '',
      motorVoltage: project.motorVoltage || '',
      motorCurrent: project.motorCurrent || '',
      ratedSpeed: project.motorSpeed || '',
      ratedTorque: project.motorTorque || '',
      workingTempMin: project.operatingTemp?.split('-')[0] || '',
      workingTempMax: project.operatingTemp?.split('-')[1] || '',
      maxPower: project.power || '',
      ratedVoltage: project.voltage || '',
      controlMode: project.controlMode || '',
      driveType: project.controlAlgorithm || '',
      communication: project.communicationProtocol || '',
      createTime: project.createTime.toISOString(),
      updateTime: project.updateTime.toISOString(),
      progress: project.level1 === 'COMPLETED' ? 100 : 
                project.level1 === 'IN_PROGRESS' ? 75 :
                project.level1 === 'REVIEW' ? 50 : 25
    }
    
    return NextResponse.json(motorProject)
  } catch (error) {
    console.error('Error fetching motor project:', error)
    return NextResponse.json(
      { error: 'Failed to fetch motor project' },
      { status: 500 }
    )
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const body = await request.json()
    
    const existingProject = await db.researchProject.findUnique({
      where: { id: params.id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }
    
    const {
      name,
      customer,
      salesperson,
      requirements,
      description,
      motorType,
      motorPower,
      motorVoltage,
      motorCurrent,
      ratedSpeed,
      ratedTorque,
      workingTempMin,
      workingTempMax,
      maxPower,
      ratedVoltage,
      controlMode,
      driveType,
      communication,
      status,
      updatedBy = 'system'
    } = body
    
    const updatedProject = await db.researchProject.update({
      where: { id: params.id },
      data: {
        projectTitle: name,
        name,
        customerName: customer,
        applicantName: salesperson,
        description: requirements,
        applicationType: description,
        level1: status?.toUpperCase() || existingProject.level1,
        updatedBy,
        updateTime: new Date(),
        
        // 电机控制参数
        motorType,
        motorPower,
        motorVoltage,
        motorCurrent,
        motorSpeed: ratedSpeed,
        motorTorque: ratedTorque,
        
        // 技术规格参数
        voltage: ratedVoltage,
        power: maxPower,
        
        // 控制模式参数
        controlMode,
        controlAlgorithm: driveType,
        communicationProtocol: communication,
        
        // 工作环境参数
        operatingTemp: workingTempMin && workingTempMax ? `${workingTempMin}-${workingTempMax}` : null
      },
      include: {
        creator: {
          select: {
            id: true,
            name: true,
            email: true
          }
        }
      }
    })
    
    // 创建历史记录
    await db.projectHistory.create({
      data: {
        projectId: project.id,
        action: 'UPDATED',
        description: '更新电机控制项目',
        userId: updatedBy,
        fromLevel1: existingProject.level1,
        toLevel1: updatedProject.level1,
        fromLevel2: existingProject.level2,
        toLevel2: updatedProject.level2
      }
    })
    
    // 返回转换后的数据格式
    const motorProject = {
      id: updatedProject.id,
      name: updatedProject.name || updatedProject.projectTitle,
      customer: updatedProject.customerName || '',
      salesperson: updatedProject.applicantName || '',
      requirements: updatedProject.description || '',
      description: updatedProject.applicationType || '',
      status: updatedProject.level1?.toLowerCase() || 'pending',
      motorType: updatedProject.motorType || '',
      motorPower: updatedProject.motorPower || '',
      motorVoltage: updatedProject.motorVoltage || '',
      motorCurrent: updatedProject.motorCurrent || '',
      ratedSpeed: updatedProject.motorSpeed || '',
      ratedTorque: updatedProject.motorTorque || '',
      workingTempMin: updatedProject.operatingTemp?.split('-')[0] || '',
      workingTempMax: updatedProject.operatingTemp?.split('-')[1] || '',
      maxPower: updatedProject.power || '',
      ratedVoltage: updatedProject.voltage || '',
      controlMode: updatedProject.controlMode || '',
      driveType: updatedProject.controlAlgorithm || '',
      communication: updatedProject.communicationProtocol || '',
      createTime: updatedProject.createTime.toISOString(),
      updateTime: updatedProject.updateTime.toISOString(),
      progress: updatedProject.level1 === 'COMPLETED' ? 100 : 
                updatedProject.level1 === 'IN_PROGRESS' ? 75 :
                updatedProject.level1 === 'REVIEW' ? 50 : 25
    }
    
    return NextResponse.json(motorProject)
  } catch (error) {
    console.error('Error updating motor project:', error)
    return NextResponse.json(
      { error: 'Failed to update motor project' },
      { status: 500 }
    )
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: { id: string } }
) {
  try {
    const existingProject = await db.researchProject.findUnique({
      where: { id: params.id }
    })
    
    if (!existingProject) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      )
    }
    
    await db.researchProject.delete({
      where: { id: params.id }
    })
    
    return NextResponse.json({ message: 'Project deleted successfully' })
  } catch (error) {
    console.error('Error deleting motor project:', error)
    return NextResponse.json(
      { error: 'Failed to delete motor project' },
      { status: 500 }
    )
  }
}